<template>
  <div class="bookshelf-page">
    <el-card
      v-for="book in bookshelf"
      :key="book.bookId"
      @click="goToLastRead(book)"
      class="book-card"
    >
      <img :src="book.coverUrl" class="cover" />
      <div class="title">{{ book.title }}</div>
    </el-card>

    <el-empty
      v-if="bookshelf.length === 0"
      description="书架为空，快去添加喜欢的图书吧～"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getShelfBook } from '@/apis/book'

const router = useRouter()
const bookshelf = ref([])

// 页面加载时从后端获取书架数据
onMounted(async () => {
  try {
    const response = await getShelfBook()
    bookshelf.value = response.data || []
  } catch (error) {
    console.error('获取书架数据失败:', error)
  }
})

// 跳转到最近阅读的章节页面
const goToLastRead = (book) => {
  if (book.lastReadChapterId) {
    router.push({
      name: 'bookChapter',
      params: {
        bookId: book.bookId,
        chapterId: book.lastReadChapterId,
      },
    })
  } else {
    // fallback：如果没有最近章节，跳转到书籍首页或详情页
    router.push(`/home/reading/book/${book.bookId}`)
  }
}
</script>

<style scoped>
.bookshelf-page {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 16px;
}

.book-card {
  width: 160px;
  cursor: pointer;
  transition: transform 0.2s;
}

.book-card:hover {
  transform: translateY(-4px);
}

.cover {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 6px;
}

.title {
  margin-top: 8px;
  text-align: center;
  font-size: 14px;
  color: #333;
}
</style>
